<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧面板 - 饼图 -->
      <el-col :span="12">
        <div class="left-module-container">
          <!-- 返回按钮放在左侧模块上方 -->
          <el-button type="text" icon="ArrowLeft" @click="goBack" class="back-btn">返回</el-button>
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>骑手订单组成分析</span>
                <span v-if="currentRider" class="rider-name">
                  {{ currentRider.rider?.name || `骑手${currentRider.riderId}` }}
                </span>
              </div>
            </template>
            <div v-if="hasData" id="orderPieChart" style="width: 100%; height: 400px"></div>
            <div v-else class="empty-chart">
              <el-empty description="暂无数据" />
            </div>
          </el-card>
        </div>
      </el-col>

      <!-- 右侧面板 - 排行榜柱状图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>骑手排行榜</span>
              <div class="rank-controls">
                <el-select
                    v-model="rankType"
                    placeholder="排行类型"
                    style="width: 120px"
                    @change="handleRankChange"
                >
                  <el-option label="抢单量" value="grabbedOrders"></el-option>
                  <el-option label="系统派单量" value="systemAssigned"></el-option>
                  <el-option label="完成单量" value="completedOrders"></el-option>
                  <el-option label="当前持单量" value="currentOrders"></el-option>
                  <el-option label="配送费" value="deliveryFee"></el-option>
                </el-select>
                <el-select
                    v-model="rankRange"
                    placeholder="排名范围"
                    style="width: 120px; margin-left: 10px"
                    @change="handleRankChange"
                >
                  <el-option label="TOP 1-10" value="1-10"></el-option>
                  <el-option label="TOP 11-20" value="11-20"></el-option>
                  <el-option label="TOP 21-30" value="21-30"></el-option>
                </el-select>
              </div>
            </div>
          </template>
          <div id="rankBarChart" style="width: 100%; height: 400px"></div>
          <div class="rank-pagination" v-if="hasData">
            <el-pagination
                small
                layout="prev, pager, next"
                :total="totalRiders"
                :page-size="10"
                :current-page="currentRankPage"
                @current-change="handleRankPageChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="RiderPerformance">
import { listStatistics } from "@/api/system/statistics"
import * as echarts from 'echarts'
import { onMounted, onBeforeUnmount, nextTick, ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 数据状态
const loading = ref(false)
const riderList = ref([])
const currentRider = ref(null)
const pieChart = ref(null)
const barChart = ref(null)
const hasData = ref(false)
const rankType = ref('grabbedOrders') // 默认显示抢单量排行
const rankRange = ref('1-10') // 默认显示1-10名
const currentRankPage = ref(1) // 当前排名页码
const totalRiders = ref(0) // 总骑手数量

// 计算当前显示的排名范围
const displayRiders = computed(() => {
  if (!riderList.value.length) return []

  // 1. 按当前选择类型降序排列
  const sortedRiders = [...riderList.value].sort((a, b) => {
    const valA = parseFloat(a[rankType.value]) || 0
    const valB = parseFloat(b[rankType.value]) || 0
    return valB - valA // 降序排列
  })

  // 2. 根据选择的排名范围截取数据
  const [start, end] = rankRange.value.split('-').map(Number)
  return sortedRiders.slice(start - 1, end)
})

/** 返回上一页 */
function goBack() {
  router.go(-1)
}

/** 更新饼图 */
function updatePieChart(riderData) {
  if (!riderData || !pieChart.value) return

  const option = {
    title: {
      text: '骑手订单组成',
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['抢单量', '系统派单量', '增派单量', '改派单量']
    },
    series: [
      {
        name: '订单组成',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: riderData.grabbedOrders || 0, name: '抢单量' },
          { value: riderData.systemAssigned || 0, name: '系统派单量' },
          { value: riderData.additionalAssigned || 0, name: '增派单量' },
          { value: riderData.reassigned || 0, name: '改派单量' }
        ]
      }
    ]
  }

  pieChart.value.setOption(option)
  pieChart.value.resize()
}

/** 更新排行榜柱状图 */
function updateRankChart() {
  if (!barChart.value || !displayRiders.value.length) return

  const rankTypeName = getRankTypeName()
  const [startRank] = rankRange.value.split('-').map(Number)

  const option = {
    title: {
      text: `骑手${rankTypeName}排行榜 TOP${rankRange.value}`,
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: params => {
        const rider = params[0].data.riderData
        const rank = startRank + params[0].dataIndex
        return `
          <div style="font-weight:bold">${rank}. ${rider.rider?.name || `骑手${rider.riderId}`}</div>
          <div>${rankTypeName}: <b>${params[0].value}</b></div>
          <div>完成单量: ${rider.completedOrders || 0}</div>
          <div>当前持单: ${rider.currentOrders || 0}</div>
        `
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '18%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: rankTypeName,
      nameLocation: 'middle',
      nameGap: 25,
      axisLabel: {
        rotate: 0,
        margin: 10
      }
    },
    yAxis: {
      type: 'category',
      data: displayRiders.value.map((rider, index) => {
        const rank = startRank + index
        return `${rank}. ${rider.rider?.name || `骑手${rider.riderId}`}`
      }),
      axisLabel: {
        interval: 0,
        rotate: 0,
        width: 80,
        overflow: 'truncate',
        ellipsis: '...'
      },
      axisTick: {
        alignWithLabel: true
      },
      inverse: true // 将Y轴反转，使第一名显示在最上方
    },
    series: [{
      name: rankTypeName,
      type: 'bar',
      data: displayRiders.value.map(rider => ({
        value: parseFloat(rider[rankType.value]) || 0,
        riderData: rider,
        itemStyle: {
          color: rider.riderId === currentRider.value?.riderId
              ? '#c23531'  // 当前选中骑手红色高亮
              : '#61a0a8'  // 其他骑手默认颜色
        }
      })),
      barWidth: '60%',
      label: {
        show: true,
        position: 'right',
        formatter: '{c}',
        color: '#333'
      },
      itemStyle: {
        borderRadius: [0, 4, 4, 0],
        borderWidth: 1,
        borderType: 'solid'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }],
    animationDuration: 1500
  }

  barChart.value.setOption(option, true)
  barChart.value.off('click')
  barChart.value.on('click', params => {
    if (params.componentType === 'series') {
      currentRider.value = params.data.riderData
      updatePieChart(currentRider.value)
      updateRankChart()
    }
  })
}

/** 获取排行类型名称 */
function getRankTypeName() {
  const names = {
    grabbedOrders: '抢单量',
    systemAssigned: '系统派单量',
    completedOrders: '完成单量',
    currentOrders: '当前持单量',
    deliveryFee: '配送费'
  }
  return names[rankType.value] || ''
}

/** 处理排名类型变化 */
function handleRankChange() {
  updateRankChart()
}

/** 处理排名分页变化 */
function handleRankPageChange(page) {
  currentRankPage.value = page
  // 根据页码更新排名范围
  if (page === 1) {
    rankRange.value = '1-10'
  } else if (page === 2) {
    rankRange.value = '11-20'
  } else {
    rankRange.value = '21-30'
  }
  updateRankChart()
}

/** 查询骑手数据 */
async function fetchRiderData() {
  try {
    loading.value = true
    const response = await listStatistics({ pageNum: 1, pageSize: 30 }) // 获取前30名数据
    console.log('API响应:', response)

    riderList.value = response.rows || []
    totalRiders.value = response.total || riderList.value.length
    hasData.value = riderList.value.length > 0

    if (hasData.value) {
      // 默认显示排行榜第一名的数据
      const sortedRiders = [...riderList.value].sort((a, b) => b[rankType.value] - a[rankType.value])
      currentRider.value = sortedRiders[0]

      await nextTick()

      // 初始化饼图
      if (!pieChart.value) {
        pieChart.value = echarts.init(document.getElementById('orderPieChart'))
        window.addEventListener('resize', () => pieChart.value?.resize())
      }
      updatePieChart(currentRider.value)

      // 初始化柱状图
      if (!barChart.value) {
        barChart.value = echarts.init(document.getElementById('rankBarChart'))
        window.addEventListener('resize', () => barChart.value?.resize())
      }
      updateRankChart()
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    proxy.$modal.msgError("获取数据失败: " + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchRiderData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => pieChart.value?.resize())
  window.removeEventListener('resize', () => barChart.value?.resize())
  pieChart.value?.dispose()
  barChart.value?.dispose()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.left-module-container {
  position: relative;
}

.back-btn {
  position: absolute;
  left: 0;
  top: -20px; /* 调整按钮位置到卡片上方 */
  z-index: 10;
  padding: 0;
}

.chart-card {
  margin-bottom: 20px;
  height: 510px;
  position: relative;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .rider-name {
      font-weight: bold;
      color: #333;
    }

    .rank-controls {
      display: flex;
      align-items: center;
    }
  }

  .empty-chart {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
  }

  .rank-pagination {
    position: absolute;
    bottom: 10px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    padding: 10px 0;
  }
}

.el-select {
  margin-left: 10px;
}
</style>